import { BinaryLike, Encoding, createHash } from 'crypto'

/**
 * 实例化对象
 * @param target
 * @param args
 * @returns
 */
export function createInstance(target: Function, ...args: any[]) {
  try {
    const obj = Object.create({})
    Object.setPrototypeOf(obj, target.prototype)
    const res = target.call(obj, ...args)

    return ['object', 'function'].includes(typeof res) ? res : obj
  } catch (e) {
    return new (target as any)(...args)
  }
}

/**
 * 获取内容MD5
 * @param data
 */
export function md5(data: BinaryLike): string
/**
 * 获取内容MD5
 * @param data
 * @param inputEncoding
 * @returns
 */
export function md5(data: string, inputEncoding?: Encoding): string {
  if (inputEncoding) {
    return createHash('md5').update(data, inputEncoding).digest('hex')
  }
  return createHash('md5').update(data).digest('hex')
}

/**
 * 是否未绝对地址
 * @param url
 * @returns
 */
export function isAbsoluteUrl(url: string) {
  return /^https?/.test(url)
}

/**
 * 拼接url地址
 * @param domain
 * @param relativeUrl
 * @returns
 */
export function joinUrl(domain: string, relativeUrl: string) {
  if (isAbsoluteUrl(relativeUrl)) {
    return relativeUrl
  } else {
    return domain.replace(/\/+$/, '') + '/' + relativeUrl.replace(/^\/+/, '')
  }
}
